package mysql

import "common/models"

func (h Mysql) MessageCheck(val *models.Message) (exist bool, info *models.Message, err error) {
	var count int64
	exist = false
	err = h.Db.Table("message_info").Where("`from` = ? and `to` =? and `type` = ?", val.From, val.To, val.Type).Count(&count).Error
	if err != nil {
		return
	}
	if count > 0 {
		exist = true
		err = h.Db.Table("message_info").Where("`from` = ? and `to` =? and `type` = ?", val.From, val.To, val.Type).First(&info).Error
	}
	return
}
func (h Mysql) MessageCheckByID(val string) (exist bool, info *models.Message, err error) {
	var count int64
	exist = false
	err = h.Db.Table("message_info").Where("id = ?", val).Count(&count).Error
	if err != nil {
		return
	}
	if count > 0 {
		exist = true
		err = h.Db.Table("message_info").Where("id = ?", val).First(&info).Error
	}
	return
}
func (m Mysql) MessageAdd(val *models.Message) (err error) {
	err = m.Db.Table("message_info").Create(&val).Error
	return
}
func (m Mysql) MessageUpdateById(val *models.Message) (err error) {
	err = m.Db.Table("message_info").Where("id = ?", val.ID).Updates(&val).Error
	return
}
func (m Mysql) MessageDeleteById(val string) (err error) {
	err = m.Db.Table("message_info").Unscoped().Where("id = ?", val).Delete(&models.Message{}).Error
	return
}
func (m Mysql) MessageSearchByFrom(val string, page, size int) (res []*models.Message, total int64, err error) {
	err = m.Db.Table("message_info").Where("`from` = ?", val).Offset((page - 1) * size).Limit(size).Find(&res).Count(&total).Error
	return
}
func (m Mysql) MessageSearchByTo(val string, page, size int) (res []*models.Message, total int64, err error) {
	err = m.Db.Table("message_info").Where("`to` = ?", val).Offset((page - 1) * size).Limit(size).Find(&res).Count(&total).Error
	return
}
